import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.io.*;

public class LoadBalancer {
	DBlist servers = new DBlist();
	DataList list = new DataList();
	
	public LoadBalancer() {
	//	servers = new DBlist();
		list = readDataList();
	}

	
	public static void main(String[] argv) throws IOException
	{
		
		final LoadBalancer lb = new LoadBalancer();
		ServerSocket lacznikSocket = new ServerSocket(5000);
		Message m = null;
		boolean klientconnected = false;
		boolean dbconnected = false;
		int id = 0;
		
		final ExecutorService threadPool = Executors.newCachedThreadPool();  
		
		while(true)
		{
			final Socket newConn  = lacznikSocket.accept();
			System.out.println("Cos przyszlo");
			
			threadPool.execute(new Runnable(){  
		            public void run(){  	
		            	identify(newConn, lb.servers, lb.list);
		            }
			});
		            
		}
		
	}
	
	public static void identify(Socket s, DBlist servers, DataList list) {
		Identifier i = new Identifier(s, servers, list);
		i.start();
	}
	
	public static DataList readDataList() {
		DataList recoveredList = new DataList();
    	try {
    	      InputStream file = new FileInputStream( "pliki.ser" );
    	      InputStream buffer = new BufferedInputStream( file );
    	      ObjectInput input = new ObjectInputStream ( buffer );
    	      recoveredList = (DataList)input.readObject();
    	      System.out.println("rozmiar odzyskanej listy: " + recoveredList.printSize());
    	      input.close();
    	} catch (FileNotFoundException e) { System.out.println("nie znaleziono pliku"); }
    	catch (Exception e) { e.printStackTrace(); }
    	return recoveredList;
    }
	
	
	public static void connectServer(LoadBalancer lb, int id, Socket s) {
		//lb.servers.addServer(id,s);
	}
	
	public static void sendMessage(LoadBalancer lb, int id, Message m) {
		//lb.servers.sendMessage(id, m);
	}
	
}